﻿using dz.loger.core;
using dz.u9.jky.schema.Common;
using dz.u9.jky.schema.Ship;
using dz.util.core;
using Dz.WorkerService.Utils;
using System.Data;

namespace Dz.WorkerService.Service
{
    /// <summary>
    /// 已对账线上发货单
    /// </summary>
    public class OnlineShipService : BaseShip
    {
        DateTime sDate, eDate;
        public OnlineShipService(string processId) : base(processId)
        {
            docType = "出货-线上订单";
        }

        

        protected async override Task<DataTable> GetProcessData()
        {
            string sql = "select distinct org,deptcode,wh,shipdate from dz_jky_SO where flag=2 and sellcount >0 and xtype=1";

            DataTable dt = await sqlUtils.Fill(sql);

            return dt;
        }

        protected override async Task Process()
        {
            foreach (DataRow dr in dt.Rows)
            {
                await Import(dr);
            }
        }

        private async Task Import(DataRow dr)
        {
            string sql = $@"select goodsno,sum(sellcount) as sellcount,sum(sellamt) as sellamt from dz_jky_SO 
                        where flag=2 and xtype=1 and sellcount > 0 and org = '{dr["org"]}' and wh = '{dr["wh"]}' 
                        and deptcode = '{dr["deptcode"]}' and shipdate = '{dr["shipdate"]}' 
                        group by goodsno ";

            DataTable result = await sqlUtils.Fill(sql);

            await Import(dr, result);
        }

        private async Task Import(DataRow dr, DataTable dt)
        {
            string org = dr["org"].ToString();
            string wh = dr["wh"].ToString();
            string dept = dr["deptcode"].ToString();
            DateTime shipdate = DateTime.Parse(dr["shipdate"].ToString()); ;

            string cust = DeptUtils.Instance.GetCust(dept, org);

            if (cust == string.Empty)
            {
                LogUtil.Instance.Error($"生成线上出货单时，通过部门{dept}，组织{org}获得客户失败。");
                return;
            }

            string extWhere = $" and org = '{org}' and wh = '{wh}' and deptcode = '{dept}' and shipdate='{shipdate}' ";

            DzShip ship = new DzShip();

            ship.DocumentType = "SM4";
            ship.OrderBy = cust;
            ship.Org = org;
            ship.TC = currencys[ship.Org];
            ship.AC = ship.TC;
            ship.IsPriceIncludeTax = true;
            ship.BusinessDate = shipdate;
            

            ship.SaleDept = dept;
            ship.Org = org;
            string taxSchedule = TaxScheduleUtils.Instance.GetTaxSchedule(ship.SaleDept, org);
            LogUtil.Instance.Debug($"taxSchedule = {taxSchedule}");
            if (taxSchedule.Length > 0) ship.TaxSchedule = taxSchedule;


            List<DzShipLine> lines = new List<DzShipLine>();
            foreach (DataRow row in dt.Rows)
            {
                DzShipLine line = new DzShipLine();

                string inv = row["goodsno"].ToString();

                if (!InvUtils.Instance.IsExists(inv, org))
                {
                    LogUtil.Instance.Debug($"存货{inv} 在U9中不存在，跳过");
                    continue;
                }
                line.DonationType = -1;
                line.ItemInfo = inv;
                line.ShipQtyInvAmount = Convert.ToDecimal(row["sellcount"]);
                //line.WH = wh;
                line.WH = "9000";
                decimal price = Convert.ToDecimal(row["sellamt"]) / Convert.ToDecimal(row["sellcount"]);
                line.OrderPrice = price;
                line.OrderPriceTC = line.OrderPrice;
                line.FinallyPrice = line.OrderPrice;
                line.FinallyPriceTC = line.OrderPrice;
                line.TaxSchedule = taxSchedule;

                if (line.OrderPrice == 0) line.DonationType = 0;

                #region 货位
                DzShipLineLocation location = new DzShipLineLocation();

                location.LocationCode = dept;
                location.LocationQtyInvAmount = line.ShipQtyInvAmount;
                location.LocationQtyTUAmount = line.ShipQtyInvAmount;
                location.Location = dept;

                List<DzShipLineLocation> locations = new List<DzShipLineLocation>() { location };
                line.ShipLineLocations = locations;
                #endregion
                lines.Add(line);
            }

            if (lines.Count == 0)
            {
                await UpdateDataState(2, extWhere);
                return;
            }

            ship.ShipLines = lines;

            //U9CResult result = await U9Utils.Post(controller, "AddAndAudit", JsonUtil.Serialize(ship));

            U9CResult result = await U9Utils.Post(controller, "Add", JsonUtil.Serialize(ship));

            await UpdateSyncLog(result, extWhere);

        }
    }
}
